package com.inesv.mqutil;

import com.rabbitmq.client.*;

import java.io.IOException;
import java.util.UUID;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.TimeoutException;
import java.util.logging.Logger;

public class ProxyUtil {
    Logger log = Logger.getLogger("proxyUtil");
    protected ConnectionFactory factory = new ConnectionFactory();
    protected Connection connection;
    String queueName;
    Channel channel;
    public ProxyUtil(String host,int port,String userName,String password,String vhost,String queueName){
        this.queueName = queueName==null?"rabbitmqserver":queueName;
        factory.setHost(host);
        factory.setPort(port);
        factory.setUsername(userName);
        factory.setPassword(password);
        factory.setVirtualHost(vhost);
        try{
            connection();
        }catch (Exception e){
            e.printStackTrace();
            log.info("=========initconnection fail===");
        }
    }
    public void connection() throws IOException, TimeoutException {
        connection = factory.newConnection();
        channel = connection.createChannel();
        channel.queueDeclare(queueName,true,false,false,null);
    }
    public String call(String message) throws IOException, InterruptedException {
        String result = "";
        String replyQueueName = channel.queueDeclare().getQueue();
        final String corrId = UUID.randomUUID().toString();
        AMQP.BasicProperties props = new AMQP.BasicProperties.Builder()
                .correlationId(corrId).replyTo(replyQueueName).build();
        channel.basicPublish("",queueName,props,"testrequest".getBytes());
        final BlockingQueue<byte[]> response = new ArrayBlockingQueue<byte[]>(1);
        channel.basicConsume(replyQueueName,true,new DefaultConsumer(channel){
            @Override
            public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException {
                System.out.println(properties.getCorrelationId());
                if (properties.getCorrelationId().equals(corrId)){
                    response.offer(body);
                }else{
                    response.offer("assssssssbbbbbb".getBytes());
                }
            }
        });
        result = new String(response.take());
        return result;
    }
}
